package com.putong35.common.httprequest;


/**
 * Copyright (c) 2012-2013, Michael Yang 杨福海 (www.yangfuhai.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import android.text.TextUtils;
import android.util.Log;

import org.apache.http.message.BasicNameValuePair;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 来源与 afinal框架中的 AjaxParams
 * <p>
 * TODO 屏蔽了文件请求参数部分
 * <p>
 * 使用方法:
 * UrlParams params = new UrlParams();
 * params.put("username", "michael");
 * params.put("password", "123456");
 * params.put("email", "test@tsz.net");
 * params.put("profile_picture", new File("/mnt/sdcard/pic.jpg")); // 上传文件
 * params.put("profile_picture2", inputStream); // 上传数据流
 * params.put("profile_picture3", new ByteArrayInputStream(bytes)); // 提交字节流
 */
public class UrlParams {
    private static String ENCODING = "UTF-8";

    protected ConcurrentHashMap<String, String> urlParams;
    protected List<FileWrapper> fileParams;

    public UrlParams() {
        init();
    }

    public UrlParams(Map<String, String> source) {
        init();
        for (Map.Entry<String, String> entry : source.entrySet()) {
            put(entry.getKey(), entry.getValue());
        }

    }

    public UrlParams(String key, String value) {
        init();
        put(key, value);
    }

    public UrlParams(Object... keysAndValues) {
        init();
        int len = keysAndValues.length;
        if (len % 2 != 0)
            throw new IllegalArgumentException("Supplied arguments must be even");
        for (int i = 0; i < len; i += 2) {
            String key = String.valueOf(keysAndValues[i]);
            String val = String.valueOf(keysAndValues[i + 1]);
            put(key, val);
        }
    }


    private void init() {
        urlParams = new ConcurrentHashMap<>();
        fileParams = new ArrayList<>();
    }


    public void put(String key, String value) {
        if (key != null && value != null) {
            urlParams.put(key, value);
        }
    }


    public void put(String key, int value) {
        if (key != null) {
            urlParams.put(key, "" + value);
        }
    }

    public void put(String key, long value) {
        if (key != null) {
            urlParams.put(key, "" + value);
        }
    }

    public void put(String key, float value) {
        if (key != null) {
            urlParams.put(key, "" + value);
        }
    }

    public void put(String key, double value) {
        if (key != null) {
            urlParams.put(key, "" + value);
        }
    }

    public void put(FileWrapper fileWrapper) {
        fileParams.add(fileWrapper);
    }

    public void put(String fileKey, File file) {
        this.put(fileKey, file, null);
    }

    /**
     * @param fileKey  Content-Disposition
     * @param file
     * @param fileType mime-type
     */
    public void put(String fileKey, File file, String fileType) {
        fileParams.add(new FileWrapper(fileKey, file, file.getName(), fileType));
    }


    public Map<String, String> getUrlParamMap() {
        return urlParams;
    }

    public List<FileWrapper> getFileParamList() {
        return fileParams;
    }

    @Override
    public String toString() {
        StringBuilder result = new StringBuilder();
        for (ConcurrentHashMap.Entry<String, String> entry : urlParams.entrySet()) {
            if (result.length() > 0)
                result.append("&");

            result.append(entry.getKey());
            result.append("=");
            result.append(entry.getValue());
        }


        if (fileParams != null && fileParams.size() > 0) {
            for (FileWrapper fileWrapper : fileParams) {
                if (result.length() > 0)
                    result.append("&");

                result.append(fileWrapper.fileKey);
                result.append("=");
                result.append("FILE");
            }
        }

        return result.toString();
    }


    /**
     * 获得参数的个数
     *
     * @return
     */
    public int getParamsCount() {
        return urlParams == null ? 0 : urlParams.size();
    }

    /**
     * Returns an HttpEntity containing all request parameters
     */
 /*   public HttpEntity getEntity() {
        HttpEntity entity = null;

        if(!fileParams.isEmpty()) {
            MultipartEntity multipartEntity = new MultipartEntity();

            // Add string params
            for(ConcurrentHashMap.Entry<String, String> entry : urlParams.entrySet()) {
                multipartEntity.addPart(entry.getKey(), entry.getValue());
            }

            // Add file params
            int currentIndex = 0;
            int lastIndex = fileParams.entrySet().size() - 1;
            for(ConcurrentHashMap.Entry<String, FileWrapper> entry : fileParams.entrySet()) {
                FileWrapper file = entry.getValue();
                if(file.inputStream != null) {
                    boolean isLast = currentIndex == lastIndex;
                    if(file.contentType != null) {
                        multipartEntity.addPart(entry.getKey(), file.getFileName(), file.inputStream, file.contentType, isLast);
                    } else {
                        multipartEntity.addPart(entry.getKey(), file.getFileName(), file.inputStream, isLast);
                    }
                }
                currentIndex++;
            }

            entity = multipartEntity;
        } else {
            try {
                entity = new UrlEncodedFormEntity(getParamsList(), ENCODING);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        return entity;
    }*/
    protected List<BasicNameValuePair> getParamsList() {
        List<BasicNameValuePair> lparams = new LinkedList<BasicNameValuePair>();

        for (ConcurrentHashMap.Entry<String, String> entry : urlParams.entrySet()) {
            lparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }

        return lparams;
    }

    public String getParamString() {
        String paramStr = "";
        for (ConcurrentHashMap.Entry<String, String> entry : urlParams.entrySet()) {
            try {
                paramStr += URLEncoder.encode(entry.getKey(), ENCODING) + "=" + URLEncoder.encode(entry.getValue(), ENCODING) + "&";
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        if (paramStr.endsWith("&")) {
            paramStr = paramStr.substring(0, paramStr.length() - "&".length());
        }

        return paramStr;
//        return URLEncodedUtils.format(getParamsList(), ENCODING);
    }

    public static String getUrlWithQueryString(String url, UrlParams params) {
        if (!TextUtils.isEmpty(url)) {
            url = url.trim();
            if (params != null && !TextUtils.isEmpty(params.getParamString())) {
                url += "?" + params.getParamString();
            }
            return url;
        }
        return "";
    }


    public static class FileWrapper {
        public File file;
        public String fileKey; // Content-Disposition中的name属性
        public String filename;
        public String contentType;

        public FileWrapper(String fileKey, File file, String fileName, String contentType) {
            this.file = file;
            this.filename = fileName;
            this.contentType = contentType;
            this.fileKey = fileKey;

            if (file == null || !file.exists()) {
                Log.d("FileWrapper", "文件" + fileName + "不存在");
            }
        }

        public String getFilename() {
            if (filename != null) {
                return filename;
            } else {
                return "nofilename";
            }
        }
    }
}